import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wan_android/generated/l10n.dart';
import 'package:flutter_wan_android/manager/router_manger.dart';
import 'package:flutter_wan_android/provider/provider_widget.dart';
import 'package:flutter_wan_android/utils/resource_mananger.dart';
import 'package:flutter_wan_android/view_model/login_model.dart';
import 'package:provider/provider.dart';
import 'package:toast/toast.dart';

import 'teddy_controller.dart';
import 'tracking_text_input.dart';

class SignIn extends StatefulWidget {
  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  TeddyController _teddyController;
  String _email = '';
  String _password = '';
  String _repeatPassword = '';
  bool _isObscured = true;
  bool _isRepeatObscured = true;
  bool _isLoading = false;
  bool _isLogin = true;

  @override
  void initState() {
    _teddyController = TeddyController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    return Scaffold(
      key: _scaffoldKey,
      body: Container(
        height: height,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomCenter,
            colors: [Theme.of(context).primaryColor, Colors.white],
          ),
        ),
        child: SingleChildScrollView(
          padding: EdgeInsets.only(top: height * 0.05),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ///顶部返回按钮
              Align(
                alignment: Alignment.topLeft,
                child: IconButton(
                  icon: Icon(
                    Icons.arrow_back,
                    color: Colors.white,
                    size: 35.0,
                  ),
                  onPressed: () {
                    RoutesManager.getInstance().pop(context);
                  },
                ),
              ),

              ///Teddy登录图
              Container(
                height: height * 0.25,
                child: FlareActor(
                  ImageHelper.wrapAnimationAssets("Teddy.flr"),
                  shouldClip: false,
                  alignment: Alignment.bottomCenter,
                  fit: BoxFit.contain,
                  controller: _teddyController,
                ),
              ),

              ///登录选项
              Container(
                height: height * 0.45,
                margin: const EdgeInsets.symmetric(horizontal: 15.0),
                padding: const EdgeInsets.symmetric(horizontal: 30.0, vertical: 5.0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(25.0),
                ),
                child: AnimatedSwitcher(
                  duration: Duration(milliseconds: 300),
                  transitionBuilder: (child, animation) => FadeTransition(
                    opacity: animation,
                    child: child,
                  ),
                  child: userWidget(),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget userWidget() {
    ///账号登录
    if (_isLogin) {
      return Column(
        key: ValueKey(1),
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ///用户名
          TrackingTextInput(
            initialValue: "cooljiatao",
            icon: Icons.person,
            enable: !_isLoading,
            label: S.of(context).userName,
            onTextChanged: (String email) {
              _email = email;
            },
            onCaretMoved: (Offset caret) {
              _teddyController.lookAt(caret);
            },
          ),

          ///密码
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                child: TrackingTextInput(
                  initialValue: "lovetao51!!",
                  label: S.of(context).userPassword,
                  isObscured: _isObscured,
                  icon: Icons.lock,
                  enable: !_isLoading,
                  onCaretMoved: (Offset caret) {
                    _teddyController.coverEyes(caret != null);
                    _teddyController.lookAt(null);
                  },
                  onTextChanged: (String password) {
                    _password = password;
                  },
                ),
              ),
              IconButton(
                icon: Icon(_isObscured ? Icons.visibility : Icons.visibility_off, color: Colors.black45),
                onPressed: () {
                  setState(() {
                    _isObscured = !_isObscured;
                  });
                },
              ),
            ],
          ),
          Padding(
              padding: EdgeInsets.only(top: 0),
              child: Row(
                children: [
                  ///忘记密码按钮
                  InkWell(
                      child: Text(
                        S.of(context).forgetPassword,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          decoration: TextDecoration.underline,
                          color: Color(0xFF888888),
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onTap: () => Toast.show(S.of(context).functionNotCompleted, context)),
                  Expanded(child: Text("")),

                  ///注册按钮
                  InkWell(
                    child: Text(
                      S.of(context).register,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        decoration: TextDecoration.underline,
                        color: Color(0xFF888888),
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onTap: () {
                      setState(() {
                        _isLogin = false;
                      });
                    },
                  ),
                ],
              )),

          ///登录按钮
          ProviderWidget<LoginModel>(
              model: LoginModel(Provider.of(context)),
              child: Builder(
                builder: (context) {
                  return RaisedButton(
                    color: Theme.of(context).primaryColor,
                    child: _isLoading
                        ? SpinKitThreeBounce(
                            color: Colors.white,
                            size: 25.0,
                          )
                        : Text(
                            S.of(context).signIn,
                            style: TextStyle(color: Colors.white),
                          ),
                    highlightElevation: 20.0,
                    onPressed: () => onLoginPressed(context),
                  );
                },
              ))
        ],
      );
    } else {
      ///账号注册
      return Column(
        key: ValueKey(2),
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          ///用户名
          TrackingTextInput(
            initialValue: "cooljiatao",
            icon: Icons.person,
            enable: !_isLoading,
            label: S.of(context).userName,
            onTextChanged: (String email) {
              _email = email;
            },
            onCaretMoved: (Offset caret) {
              _teddyController.lookAt(caret);
            },
          ),

          ///密码
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                child: TrackingTextInput(
                  initialValue: "lovetao51!!",
                  label: S.of(context).userPassword,
                  isObscured: _isObscured,
                  icon: Icons.lock,
                  enable: !_isLoading,
                  onCaretMoved: (Offset caret) {
                    _teddyController.coverEyes(caret != null);
                    _teddyController.lookAt(null);
                  },
                  onTextChanged: (String password) {
                    _password = password;
                  },
                ),
              ),
              IconButton(
                icon: Icon(_isObscured ? Icons.visibility : Icons.visibility_off, color: Colors.black45),
                onPressed: () {
                  setState(() {
                    _isObscured = !_isObscured;
                  });
                },
              ),
            ],
          ),

          ///确认密码
          Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Expanded(
                child: TrackingTextInput(
                  initialValue: "lovetao51!!",
                  label: S.of(context).userRepeatPassword,
                  isObscured: _isRepeatObscured,
                  icon: Icons.lock,
                  enable: !_isLoading,
                  onCaretMoved: (Offset caret) {
                    _teddyController.coverEyes(caret != null);
                    _teddyController.lookAt(null);
                  },
                  onTextChanged: (String password) {
                    _repeatPassword = password;
                  },
                ),
              ),
              IconButton(
                icon: Icon(_isRepeatObscured ? Icons.visibility : Icons.visibility_off, color: Colors.black45),
                onPressed: () {
                  setState(() {
                    _isRepeatObscured = !_isRepeatObscured;
                  });
                },
              ),
            ],
          ),
          Padding(
              padding: EdgeInsets.only(top: 0),
              child: Row(
                children: [
                  ///忘记密码按钮
                  InkWell(
                      child: Text(
                        S.of(context).forgetPassword,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          decoration: TextDecoration.underline,
                          color: Color(0xFF888888),
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onTap: () => Toast.show(S.of(context).functionNotCompleted, context)),
                  Expanded(child: Text("")),

                  ///登录按钮
                  InkWell(
                    child: Text(
                      S.of(context).signIn,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        decoration: TextDecoration.underline,
                        color: Color(0xFF888888),
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onTap: () {
                      setState(() {
                        _isLogin = true;
                      });
                    },
                  ),
                ],
              )),

          ///注册按钮
          ProviderWidget<LoginModel>(
              model: LoginModel(Provider.of(context)),
              child: Builder(
                builder: (context) {
                  return RaisedButton(
                    color: Theme.of(context).primaryColor,
                    child: _isLoading
                        ? SpinKitThreeBounce(
                            color: Colors.white,
                            size: 25.0,
                          )
                        : Text(
                            S.of(context).signIn,
                            style: TextStyle(color: Colors.white),
                          ),
                    highlightElevation: 20.0,
                    onPressed: () => onRegisterPressed(context),
                  );
                },
              ))
        ],
      );
    }
  }

  ///
  /// 用户登录点击
  ///
  void onLoginPressed(BuildContext context) async {
    if (_teddyController.isPlayedAnimation("hands_up")) {
      _teddyController.coverEyes(false);
      await Future.delayed(Duration(milliseconds: 800));
    }

    if (_email.isEmpty || _password.isEmpty) {
      _showSnackBar(S.of(context).signInInfoEmpty);
      _teddyController.play('fail');
    } else {
      ///修改登录按钮样式
      _isLoading = true;
      setState(() {});

      ///开始登录
      _checkLoginEmailPassword(context);
    }
  }

  ///
  /// 服务器登录
  ///
  Future _checkLoginEmailPassword(BuildContext context) async {
    await Future.delayed(Duration(seconds: 1));

    return Provider.of<LoginModel>(context, listen: false).login(_email, _password).then((value) {
      _teddyController.play("success");
      _signInSuccess();
    }, onError: (error) {
      _teddyController.play("fail");
      _signInFailed(error.toString());
    });
  }

  ///
  /// 用户注册点击
  ///
  void onRegisterPressed(BuildContext context) async {
    if (_teddyController.isPlayedAnimation("hands_up")) {
      _teddyController.coverEyes(false);
      await Future.delayed(Duration(milliseconds: 800));
    }

    if (_email.isEmpty || _password.isEmpty || _repeatPassword.isEmpty) {
      _showSnackBar(S.of(context).signInInfoEmpty);
      _teddyController.play('fail');
    } else if (_password != _repeatPassword) {
      _showSnackBar(S.of(context).passwordNotMatch);
    } else {
      ///修改登录按钮样式
      _isLoading = true;
      setState(() {});

      ///开始登录
      _checkRegisterEmailPassword(context);
    }
  }

  ///
  /// 服务器登录
  ///
  Future _checkRegisterEmailPassword(BuildContext context) async {
    await Future.delayed(Duration(seconds: 1));

    return Provider.of<LoginModel>(context, listen: false).register(_email, _password, _repeatPassword).then((value) {
      _teddyController.play("success");
      _signInSuccess();
    }, onError: (error) {
      _teddyController.play("fail");
      _signInFailed(error.toString());
    });
  }

  ///
  /// 登录成功
  ///
  void _signInSuccess() async {
    _showSnackBar(S.of(context).signInSuccess);

    await Future.delayed(Duration(seconds: 2));
    RoutesManager.getInstance().pop(context);
  }

  ///
  /// 登录失败
  ///
  void _signInFailed(String errMsg) {
    _showSnackBar(errMsg);
    _isLoading = false;
    setState(() {});
  }

  void _showSnackBar(String title) => _scaffoldKey.currentState.showSnackBar(
        SnackBar(
          backgroundColor: Theme.of(context).primaryColor,
          content: Text(title, textAlign: TextAlign.center),
        ),
      );
}
